package com.syg.route;

import com.syg.service.MySqlRouteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * Spring Cloud Gateway 通过定义 RouteDefinitionRepository 来实现动态路由.
 *
 * 可以仿造InMemoryRouteDefinitionRepository(spring提供的) 来实现
 */
@Slf4j
@Component
public class MySqlRouteDefinitionRepository implements RouteDefinitionRepository {

    @Resource
    MySqlRouteService mySqlRouteService;

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        List<RouteDefinition> routeDefList =mySqlRouteService.getRouteDefinitions();
        if(CollectionUtils.isEmpty(routeDefList)){
            log.error("获取到路由配置为:NULL");
            return null;
        }

        log.info("获取到路由配置为:{}", routeDefList);
        return Flux.fromIterable(routeDefList);
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return mySqlRouteService.save(route);
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return mySqlRouteService.delete(routeId);
    }

}
